import com.mit.web.business.proxy.MaintenanceProxy;
import com.mit.web.business.remote.IInvokeResponder;
import com.mit.web.config.Constants;
import com.mit.web.config.DisplayConfiguration;
import com.mit.web.event.ClickGridCheckBoxEvent;
import com.mit.web.event.PopWinCloseEvent;
import com.mit.web.model.maintenance.EmployeeEnquiryModel;
import com.mit.web.util.LogUtil;
import com.mit.web.util.MessageUtil;
import com.mit.web.view.component.monitor.IProgressMonitor;
import com.mit.web.view.component.monitor.ProgressBarMonitor;
import com.mit.web.view.maintenance.EmployeeEditForm;
import com.mit.web.vo.maintenance.EmployeeVO;

import flash.events.Event;
import flash.events.MouseEvent;

import flexlib.controls.SuperTabBar;
import flexlib.controls.tabBarClasses.SuperTab;

import mx.collections.ArrayCollection;
import mx.containers.Panel;
import mx.controls.Alert;
import mx.core.INavigatorContent;
import mx.events.DataGridEvent;
import mx.events.FlexEvent;
import mx.events.ListEvent;
import mx.logging.ILogger;
import mx.managers.PopUpManager;
import mx.messaging.messages.ErrorMessage;
import mx.resources.ResourceManager;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;

import spark.components.Button;
import spark.components.ButtonBar;
import spark.components.ToggleButton;

[Bindable] private var employeeEnquiryModel:EmployeeEnquiryModel;
private var _pm:IProgressMonitor;
private var _logger:ILogger;

private var maintenanceProxy:MaintenanceProxy = MaintenanceProxy.getInstance();
private const INDEX_OF_SEARCH_PANEL:int = 1;

private function init(event:FlexEvent):void{
	_logger = LogUtil.getLogger(this);
	_logger.debug("DataGrid created, load all records");
	
	employeeEnquiryModel = new EmployeeEnquiryModel();
	_pm = new ProgressBarMonitor();
	
	//set default row count. you can set in dataGrid tag
//	empDataGrid.rowCount = com.mit.web.config.DisplayConfiguration.getInstance().DEFAULT_ROW_COUNT;
	
	//Search all records
	doEnquiry();
}

/*********** Business Method ************/
private function doEnquiry(searchCode:String = null, searchDep:int = 0, page:int = 1):void{
	var responder1:IInvokeResponder = maintenanceProxy.getEmployees().installProgressBar(_pm, this);
	responder1.addResultListener(getEmployeesHandler);
	responder1.addFaultListener(exceptionHandler);

	var responder2:IInvokeResponder = maintenanceProxy.getEmployeesCount(searchCode
		, searchDep);
	responder2.addResultListener(getEmployeesCountHandler, searchCode, page);
	responder2.addFaultListener(exceptionHandler);	
	
}

private function getEmployeesCountHandler(event:ResultEvent, searchCode:String, pageNo:int):void{
	var recordCount:int = event.result as int;
	//If no record return, do not update total record count!
	if(recordCount > 0){
		employeeEnquiryModel.recordCount = recordCount;
		//If record found, save searching criteria in Model
//		employeeEnquiryModel.searchDep = box_searchDep.selectedItem;
	//	employeeEnquiryModel.searchEmpCode = searchCode;
		employeeEnquiryModel.pageNo = pageNo;
		//Refresh pagination;
//		if(paging.pageNo != employeeEnquiryModel.pageNo)
//			paging.pageNo = employeeEnquiryModel.pageNo;
	}
}

/*********** Event Handler ************/

private function getEmployeesHandler(event:ResultEvent):void{
	var list:ArrayCollection = event.result as ArrayCollection;	
	_logger.debug("employee list: " + list);
	if(list != null && list.length > 0) {
		employeeEnquiryModel.empList = list;
		empDataGrid.validateNow();
	} else {
		empDataGrid.validateNow();
		MessageUtil.popNoRecordMessage(this);
	}	
}

/**
 * click new button
 * */
protected function bnt_new_clickHandler(event:MouseEvent):void
{
	var window:EmployeeEditForm = new EmployeeEditForm();	 
	window.addEventListener(PopWinCloseEvent.CREATED, createRecordHandler);
	window.title = "用户资料";
	PopUpManager.addPopUp(window,this,true);
	PopUpManager.centerPopUp(window);
}
/*private function createRecordHandler(event:PopWinCloseEvent):void{
	showMessageTip(event.msg, empDataGrid);
	// retrieve data
	doEnquiry();
}
*/

/**
 * double click one row 
 * */
private function doEdit(event:ListEvent):void{
	var item:Object = empDataGrid.selectedItem;
	_logger.debug("edit employee: " + item);
	if(item){
		var id:int = item.id;
		var window:EmployeeEditForm = new EmployeeEditForm();	 
		//window.addEventListener(PopWinCloseEvent.DELETED, editRecordHandler);
		window.addEventListener(PopWinCloseEvent.SAVED, editRecordHandler);
		window.title = "用户资料";
		window.empId = id;
		PopUpManager.addPopUp(window,this,true);
		PopUpManager.centerPopUp(window)
	}
}

private function editRecordHandler(event:PopWinCloseEvent):void{
	//直接用保存后的VO替换，不重新读取数据库
	var savedEmp:EmployeeVO = event.vo as EmployeeVO;
	var src:Array = employeeEnquiryModel.empList.source;
	src[empDataGrid.selectedIndex] =  savedEmp;
	var updatedLst:ArrayCollection = new ArrayCollection(src);
	employeeEnquiryModel.empList = updatedLst;
	empDataGrid.validateNow();
	//显示成功提示
	showMessageTip(event.msg, empDataGrid);
}

private function createRecordHandler(event:PopWinCloseEvent):void{
	//新建的VO插入第一个元素
	var src:Array = employeeEnquiryModel.empList.source;
	var savedEmp:EmployeeVO = event.vo as EmployeeVO;
	src.unshift(savedEmp);
	//如果一页满了就移除最后一个记录-- pending，it may be a bad behavior
	//src.pop();
	var updatedLst:ArrayCollection = new ArrayCollection(src);
	employeeEnquiryModel.empList = updatedLst;
	empDataGrid.validateNow();
	//显示成功提示
	showMessageTip(event.msg, empDataGrid);
}

/*
private function editRecordHandler(event:PopWinCloseEvent):void{
	showMessageTip(event.msg, empDataGrid);
	doEnquiry();
//	doEnquiry(employeeEnquiryModel.searchCode, _model.searchState, _model.pageNo);
	//TODO: how to set the updated row as default in datagrid
}
*/

//protected function btn_edit_clickHandler(event:MouseEvent):void
//{
//	var form:EmployeeEditForm = new EmployeeEditForm();
//
//	PopUpManager.addPopUp(form,this,false);
//	PopUpManager.centerPopUp(form);
//}

protected function gridItemSelected(event:Event):void{
	var hasItemSelected:Boolean = false;
	for each(var emp:Object in employeeEnquiryModel.empList){
		if(emp.isSelected){
			hasItemSelected = true;
			break;
		}
	}
//	btn_delete.enabled = hasItemSelected;
}
